/*
 * JBeagle - a Java toolkit for genetic algorithms.
 * 
 * Copyright (c) 2010 Matthijs Snel
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package jbeagle.core.select;

import jbeagle.core.Individual;
import jbeagle.core.Population;

public class StochasticUniversalSamplingSelector implements Selector {

	public <I extends Individual<G>, G> Population<I, G> apply( Population<I, G> pop ) {
		double	d = Math.random(),
				sum = 0,
				avg = pop.getAvgFitness();
		
		int i = 0;
		
		Population<I, G> nextPop = new Population<I, G>(pop.size());
		
		//Algorithm from Mitchell, chapter 5
		for ( sum = i = 0; i < pop.size(); i++ )
			for ( sum += expectedVal(pop.get(i), avg); sum > d; d++ )
				nextPop.add( (I) pop.get(i).copy() );

		return nextPop;
	}
	
	public void setRate( double rate ) {
		throw new UnsupportedOperationException();
	}
	
	public double getRate() {
		throw new UnsupportedOperationException();
	}
	
	@SuppressWarnings("unchecked") //only using fitness here so type-safe
	protected double expectedVal( Individual ind, double avg ) {
		return ind.getFitness() / avg;
	}
}
